package com.kwlt.smc.service;

import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import com.kwlt.smc.entity.PipelineResponse;
import com.kwlt.smc.util.Constants;
import com.kwlt.smc.util.ModelConvJson;

public class JedisService<T> {
	
	private Jedis jedis;
	
	private String host;
	
	private String password;
	
	
	public JedisService(String host,String password){
		jedis = new Jedis(host);
		jedis.auth(password);
		//切换到1的数据库上，默认是0
	}
	
	public Jedis getJedis(){
		return jedis;
	}
	
	
	public T popList(String key, Class<T> c){
		ModelConvJson<T> modelConvJson = new ModelConvJson<T>();
		List<String> list = jedis.blpop(10, key);
		T t = null;
		if(list!=null){
			String json = list.get(1);
			t = modelConvJson.getModelObject(json, c);
		}
		return t;
	}
	
	/**
	 * @param key 黑名单key
	 * @param dest 手机号码串
	 * @return
	 */
	public List<PipelineResponse<Boolean>> hexists(String key,String dest){
		Pipeline pl = jedis.pipelined();
		List<PipelineResponse<Boolean>> result = new ArrayList<PipelineResponse<Boolean>>();
		if(dest!=null && !"".equals(dest)){
			for(String phone:dest.split(Constants.REXG)){
				PipelineResponse<Boolean> pr = new PipelineResponse<Boolean>();
				Response<Boolean> response = pl.hexists(key, phone);
				pr.setResponse(response);
				pr.setPhone(phone);
				result.add(pr);
			}
			pl.sync();
		}
		return result;
	}
	
	public void setHash(String key,String field,String value){
		jedis.hset(key, field, value);
	}
	
	/**
	 * 查询hash
	 * @param key
	 * @param field
	 * @return
	 */
	public String getHash(String key,String field){
		String hget = jedis.hget(key, field);
		return hget;
	}
	
	/**
	 * 保存LIST
	 * @param key
	 * @param list
	 */
	public void pushList(String key,String...list) {
		jedis.rpush(key,list);
	}
	
	
	/**
	 * 保存记数
	 * @param key
	 * @param count
	 */
	public Long saveCount(String key,int count){
		Long incrBy = jedis.incrBy(key,count);
		return incrBy;
	}
	
	/**
	 * 保存字符串
	 * @param key
	 * @param value
	 */
	public void saveString(String key,String value){	
		jedis.set(key, value);
	}
	
	/**
	 * 返回多个字符串
	 * @param keys
	 * @return
	 */
	public List<String> getStrings(String... keys){
		List<String> list = jedis.mget(keys);
		return list;
	}
	/**
	 * 返回单个字符串
	 * @param key
	 * @return
	 */
	public String getString(String key){
		String string = jedis.get(key);
		return string;
	}
	
	/**
	 * 删除key
	 * @param keys
	 */
	public void delKey(String...keys){
		jedis.del(keys);
	}
	
	public void closeJedis(){
		jedis.disconnect();
	}
}
